package fournitures;

import java.net.ServerSocket;
import java.io.IOException;

public class Port {

    /* This class represents a port on the computer where the program
       is running. If the port is claimed, it can accept connections.
       A port can be claimed only by one process at a time. Don't
       forget to release the port if you want other processes to use
       it. */

    public int portNumber;
    public ServerSocket serverSocket;

    public Port (int portNumber) {
        this.portNumber = portNumber;
    }

    public void claim () {
        // Claim this port and associate a ServerSocket with it.
        try {
            serverSocket = new ServerSocket(portNumber);
        }
        catch (IOException e) {
            System.out.println("An exception was thrown while creating a ServerSocket for port " + portNumber);
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
    
    public void claimNext () {
    	// Claim this port and associate a ServerSocket with it.
        boolean done=false;
        while(!done)
    	try {
            serverSocket = new ServerSocket(portNumber);
            done=true;
        }
        catch (IOException e) {
        	System.out.println("An exception was thrown while creating a ServerSocket for port " + portNumber);
        	if(portNumber<=65535){
        		portNumber++;
        	}
        	else{
        		throw new RuntimeException();
        	}
        }
    }
    
    public void release () {
        // Release this port by closing its ServerSocket. This means
        // the port can now be claimed by other processes.
        try {
            serverSocket.close();
        }
        catch (IOException e) {
            System.out.println("An exception was thrown while releasing the port.");
            e.printStackTrace();
            throw new RuntimeException();
        }
    }
}
